package com.beiding.dao;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class MessageDaoImpl implements MessageDao {


    //考虑使用缓存

    private String zuulId;

    //使用redis实现

    //用来存储对应的用户的未上线消息
    private ListOperations<String, String> messages;

    //用来删除某个用户的消息包
    private RedisTemplate<String, String> redisTemplate;

    //hash的值部分是用户在哪个服务里面上线
    private HashOperations<String, String, String> users;

    public MessageDaoImpl(RedisConnectionFactory factory, Environment environment) {

        zuulId = environment.getProperty("zuulId");

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

        redisTemplate.setKeySerializer(stringRedisSerializer);

        redisTemplate.setValueSerializer(stringRedisSerializer);

        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        redisTemplate.setHashValueSerializer(stringRedisSerializer);

        users = redisTemplate.opsForHash();

        redisTemplate.afterPropertiesSet();

        messages = redisTemplate.opsForList();

    }

    //用户下线
    @Override
    public void removeOnlineUser(String name) {

        //移除上线用户
        users.delete("users:onlineUser", name);
    }

    //用户上线的时候会以当前zuul服务的id作为值
    @Override
    public void addOnlineUser(String name) {
        users.put("users:onlineUser", name, zuulId);
    }


    @Override
    public void saveMessage(String receiver, String target, String payload) {
        messages.rightPush("message:" + target + ":" + receiver, payload);
    }

    @Override
    public List<String> getAndRemoveMessages(String receiver, String target) {

        String key = "message:" + target + ":" + receiver;

        List<String> list = messages.range(key, 0, -1);

        redisTemplate.delete(key);

        return list;
    }

    //获取接受者所在的服务
    @Override
    public String getOnlineServer(String receiver) {
        return users.get("users:onlineUser", receiver);
    }


}
